package com.boc.langxiang.ui.activity.shop;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.boc.langxiang.R;
import com.boc.langxiang.contract.common.AddressManageContract;
import com.boc.langxiang.contract.shop.OrderBillingContract;
import com.boc.langxiang.contract.shop.PostOrderContract;
import com.boc.langxiang.entity.bean.OrderInfo;
import com.boc.langxiang.entity.bean.ShoppingCarInfo;
import com.boc.langxiang.entity.events.AddAddressSuccessEvent;
import com.boc.langxiang.entity.response.AddressEntity;
import com.boc.langxiang.entity.response.AddressListContent;
import com.boc.langxiang.entity.response.BaseResponse;
import com.boc.langxiang.entity.response.OrderBillingResponse;
import com.boc.langxiang.entity.response.PostOrderContent;
import com.boc.langxiang.manager.PicassoImageLoader;
import com.boc.langxiang.presenter.common.AddressManagePresenter;
import com.boc.langxiang.presenter.shop.OrderBillingPresenter;
import com.boc.langxiang.presenter.shop.PostOrderPresenter;
import com.boc.langxiang.ui.activity.BaseToolBarActivity;
import com.boc.langxiang.ui.activity.common.AddAddressActivity;
import com.boc.langxiang.ui.activity.common.AddressManageActivity;
import com.boc.langxiang.ui.dialog.OnPayCancelOrSuccess;
import com.boc.langxiang.ui.dialog.OrderPayDialog;
import com.boc.langxiang.util.T;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 确认订单
 */
public class OrderConfirmActivity extends BaseToolBarActivity implements OrderBillingContract.View, View.OnClickListener {

    @BindView(R.id.icon_address)
    ImageView iconAddress;
    @BindView(R.id.address_info_layout)
    RelativeLayout addressInfoLayout;
    @BindView(R.id.non_address_tv)
    TextView nonAddressTv;
    @BindView(R.id.arrow)
    ImageView arrow;
    @BindView(R.id.products_recycler)
    RecyclerView productsRecycler;
    @BindView(R.id.commit_order)
    RelativeLayout commitOrder;
    @BindView(R.id.bottom_bar)
    RelativeLayout bottomBar;
    @BindView(R.id.total_amount_tv)
    TextView totalAmountTv;
    @BindView(R.id.name_tv)
    TextView nameTv;
    @BindView(R.id.phone_tv)
    TextView phoneTv;
    @BindView(R.id.address_tv)
    TextView addressTv;

    private String ids;

    private OrdersAdapter productsAdapter;

    private AddressEntity mAddressEntity = null;

    private final int _Address_Select = 1002;
    private boolean mNoDefaultAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_confirm);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        if (getIntent() != null && getIntent().getStringExtra("ids") != null) {
            ids = getIntent().getStringExtra("ids");
        }
        iniViews();
    }

    private void iniViews() {
        productsAdapter = new OrdersAdapter(new ArrayList<ShoppingCarInfo>());
//        salonAdapter = new OrdersAdapter(new ArrayList<ShoppingCarInfo>());
        productsRecycler.setLayoutManager(new LinearLayoutManager(this));
//        salonRecycler.setLayoutManager(new LinearLayoutManager(this));

        productsRecycler.setAdapter(productsAdapter);
//        salonRecycler.setAdapter(salonAdapter);

        addressInfoLayout.setOnClickListener(this);
        nonAddressTv.setOnClickListener(this);
        commitOrder.setOnClickListener(this);

        getData();
    }

    private void getData() {
        new OrderBillingPresenter(this).getList(ids);
        new AddressManagePresenter(new AddressManageContract.View() {
            @Override
            public void onGetAddressSuccess(BaseResponse<AddressListContent> response) {
                if (response.getContent().getAddrList().size() > 0) {
//                    address_status = _Address_Select;
                    for (int i = 0; i < response.getContent().getAddrList().size(); i++) {
                        if (response.getContent().getAddrList().get(i).getIs_default().equals("1")) {
                            mAddressEntity = response.getContent().getAddrList().get(i);
                        }
                    }
                    if (mAddressEntity == null) {
                        mNoDefaultAddress = true;
                    }
                    setAddressData();
                } else {
                    nonAddressTv.setVisibility(View.VISIBLE);
                    addressInfoLayout.setVisibility(View.GONE);
//                    address_status = _Address_NONE;
                }
            }

            @Override
            public void showDeleteLoading() {
            }

            @Override
            public void onDeleteAddressSuccess() {
            }

            @Override
            public void setDefaultAddr(int id) {
            }

            @Override
            public void showSetDefaultLoading() {
            }

            @Override
            public void setDefaultAddressSuccess() {
            }

            @Override
            public void showLoading() {
            }

            @Override
            public void hideLoading() {
            }

            @Override
            public void onError(String code, String msg) {
            }
        }).getAddressList();
    }

    @Override
    protected boolean isSetTypeFace() {
        return true;
    }

    @Override
    protected void onCreateCustomToolBar(Toolbar toolbar) {
        super.onCreateCustomToolBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.icon_return_black);
        toolbar.setBackgroundColor(Color.WHITE);
        setToolBarTitle("确认订单");
    }

    @Override
    public void onSuccess(OrderBillingResponse response) {
        View productHeader = getLayoutInflater().inflate(R.layout.shopping_car_item, productsRecycler, false);
        View salonHeader = getLayoutInflater().inflate(R.layout.shopping_car_item, productsRecycler, false);
        ((TextView) productHeader.findViewById(R.id.type_tv)).setText("商品");
        ((TextView) salonHeader.findViewById(R.id.type_tv)).setText("沙龙");

        if (response.getContent().getProductlist().size() > 0) {
            productsAdapter.addHeaderView(productHeader);
            productsAdapter.setNewData(response.getContent().getProductlist());
            productsAdapter.notifyDataSetChanged();
        }

//        if (response.getContent().getShalonglist().size() > 0) {
//            salonAdapter.addHeaderView(salonHeader);
//            salonAdapter.setNewData(response.getContent().getShalonglist());
//            salonAdapter.notifyDataSetChanged();
//        }

        double total_amount = response.getMoney();
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        totalAmountTv.setText(decimalFormat.format(total_amount));

    }

    @Override
    public void showLoading() {
        showProgressDialog("加载中，请稍候...");
    }

    @Override
    public void hideLoading() {
        hideDialog();
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(mContext, msg);
    }

    private void setAddressData() {
        if (mAddressEntity == null) {
            nonAddressTv.setVisibility(View.VISIBLE);
            addressInfoLayout.setVisibility(View.GONE);
            nonAddressTv.setText("您还没有设置默认地址，请到地址列表选择");
        } else {
            nonAddressTv.setVisibility(View.GONE);
            addressInfoLayout.setVisibility(View.VISIBLE);
            nameTv.setText(mAddressEntity.getUsername());
            phoneTv.setText(mAddressEntity.getPhone());
            addressTv.setText(mAddressEntity.getProvince() + mAddressEntity.getCity() + mAddressEntity.getDistrict() + mAddressEntity.getAddress());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddAddressSuccessEvent(AddAddressSuccessEvent event) {
        mAddressEntity = event.getAddressEntity();
        setAddressData();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == _Address_Select && resultCode == RESULT_OK && data != null) {
            mAddressEntity = data.getParcelableExtra("data");
            setAddressData();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.address_info_layout:
//                intent = new Intent(this, AddressSelectorActivity.class);
                intent = new Intent(this, AddressManageActivity.class);
                intent.putExtra("selectAddress", true);
                startActivityForResult(intent, _Address_Select);
                break;
            case R.id.non_address_tv:
                if (mNoDefaultAddress) {
//                    intent = new Intent(this, AddressSelectorActivity.class);
                    intent = new Intent(this, AddressManageActivity.class);
                    intent.putExtra("selectAddress", true);
                    startActivityForResult(intent, _Address_Select);
                } else {
                    intent = new Intent(this, AddAddressActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.commit_order:
                orderCommit();
                break;
        }
    }

    private void orderCommit() {
        if (mAddressEntity == null) {
            onError(null, "请选择收件地址");
            return;
        }
        new PostOrderPresenter(new PostOrderContract.View() {
            @Override
            public void onSuccess(BaseResponse<PostOrderContent> response) {
                orderPay(response.getContent().getOrder());
            }

            @Override
            public void showLoading() {
                showProgressDialog("订单提交中...");
            }

            @Override
            public void hideLoading() {
                hideDialog();
            }

            @Override
            public void onError(String code, String msg) {
                T.showShort(mContext, msg);
            }
        }).post(ids, String.valueOf(mAddressEntity.getId()));
    }

    private void orderPay(OrderInfo orderInfo) {
        OrderPayDialog orderPayDialog = new OrderPayDialog(mContext, orderInfo);
        orderPayDialog.setOnPayCancelOrSuccess(new OnPayCancelOrSuccess() {
            @Override
            public void onCancel() {
                finish();
            }

            @Override
            public void onSuccess() {
                finish();
            }
        });
        orderPayDialog.show();

        Window win = orderPayDialog.getWindow();
        win.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        win.setAttributes(lp);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private class OrdersAdapter extends BaseQuickAdapter<ShoppingCarInfo> {

        public OrdersAdapter(List<ShoppingCarInfo> list) {
            super(R.layout.item_order_billing, list);
        }

        @Override
        protected void convert(BaseViewHolder helper, ShoppingCarInfo item) {
            helper.setText(R.id.title_tv, item.getTitle());
            helper.setText(R.id.price_tv, "￥" + item.getPrice());
            helper.setText(R.id.num_tv, item.getNumber());
            if (item.getRemark() != null) {
                helper.setText(R.id.size_tv, item.getRemark());
            }

            PicassoImageLoader.getInstance().displayUrlImage(mContext, item.getPhotourl()
                    , (ImageView) helper.getView(R.id.product_img_iv));
        }
    }
}
